package com.meteor.web.admin;

import com.meteor.pojo.User;
import com.meteor.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Resource
    private UserService userService;

    /**
     * 跳转登录页面
     */
    @GetMapping()
    public String loginPage() {
        return "admin/login";
    }

    /**
     * 转到登录欢迎页
     */
    @GetMapping("/logIndex")
    public String logIndex() {
        return "admin/logIndex";
    }

    /**
     * 用户登录实现
     */
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password,
                        HttpSession session, RedirectAttributes attributes) {
        User user = userService.queryUserByNameAndPwd(username, password);
        if(user != null) {
            //说明查询到了这个username
            user.setPassword(null);
            session.setAttribute("user",user);
            return "admin/logIndex";
        } else {
            //说明账号密码有问题
            attributes.addFlashAttribute("message","用户名和密码错误");
            return "redirect:/admin";
        }
    }

    /**
     * 注销退出功能实现
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }

}






























